<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product extends AppController {

	public function __construct(){
		parent::__construct();
	}
	
	public function view($id = null){
		if(empty($id))
			redirect('/');
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneBy(array(
			'id' => $id,
			'status' => 1
		));
		if(empty($product))
			redirect('/');
			
		$p_extension = $this->getEM()->getRepository('Entity\ShProduct')->findExtension($product->getId());
		$this->data['similar'] = $this->getEM()->getRepository('Entity\ShProduct')->findSimilar($product->getId(), $product->getCategory()->getId());
		
		$this->data['product'] = $product;
		$this->data['color'] = $p_extension['color'];
		$this->data['size'] = $p_extension['size'];
		$this->render('product/view');
	}
	
	public function ngData($id = null){
		$product = $this->getEM()->getRepository('\Entity\ShProduct')->findOneById($id);
		$data = array(
			'id' => $product->getId(),
			'name' => $product->getName(),
			'content' => $product->getContent(),
			'status' => (($product->getQuantity()<=-1)?"Hết hàng":"Còn hàng"),
			'qty'  => $product->getQuantity(),
			'price' => $product->getPrice()
		);
		$img = $product->getImage();
		if(empty($img))
			$data['img'] = base_url('/assets/img/notfound.jpg');
		else
			$data['img'] = base_url('/assets/upload/thumbs/'.$img->getName());
		exit(json_encode($data));
	}
	public function ngView(){
		// $this->isAjax();
		$this->layout = '';
		$this->render('product/ngView');
	}

	public function search(){
		$q = $this->input->post('q');

		if(empty($q)):
			$q = urldecode($this->input->get('q'));
			if(empty($q)){
				redirect(site_url('/'));
			}
		endif;

		$sortBy = $this->input->get('sortBy');
		if(empty($sortBy))
			$sortBy = 'stt';
		$sortByDefault = array('name' => 'ten', 'id' => 'stt', 'price' => 'gia');
		
		$sortOrder = $this->input->get('sortOrder');
		if(empty($sortOrder))
			$sortOrder = 'desc';
		$sortOrderByDefault = array('desc' => 'desc', 'asc' => 'asc');
		
		$sortByVal = array_search($sortBy, $sortByDefault);
		if($sortByVal === false)
			$sortByVal = 'id';
		
		$sortOrderVal = array_search($sortOrder, $sortOrderByDefault);
		if($sortOrderVal === false)
			$sortOrderVal = 'desc';
			
		$pag= array(
			'uri_segment'=>3,
			'per_page'=>12,
			'sortList'=>array('stt'=>'id','Tên Loại'=>'name','Kích hoạt'=>'active','Sort'=>'sort'),
			'base_url'=>'/product/search',
			'sortBy'=>$sortByVal,
			'sortOrder'=>$sortOrderVal,
			'get' => array(
				'sortBy'=>$sortBy,
				'sortOrder'=>$sortOrder,
				'q' => urlencode($q)
			),
		);
		
		$pag = $this->paginate($pag);
		$this->pagination->suffix = $pag['query'];

		$data = $this->getEM()->getRepository('Entity\ShProduct')->front_search_product($q, $pag);

		$pag['total_rows'] = $data['count'];
		
		// var_dump($pag['total_rows']);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['product'] = $data['result'];
		
		$this->data['pag'] = $pag;
		$this->render('category/view');
	}

	public function admin_index($sortBy = 'id', $sortOrder = 'desc'){
		$pag  = array(
			'table' => 'Product',
			'uri_segment' => 6,
			//de sau
			'sort' => true,
			//so luong item tren 1 page
			'per_page' =>12,
			//de say
			'sortList'=>array('stt'=>'id','name'=>'name','ngay'=>'date','binh-luan'=>'comment','luot-xem'=>'view','nhap'=>'draft'),
			'base_url' => '/admin/product/index',
			//de sau
			'sortBy' => $sortBy, 'sortOrder' => $sortOrder
		);

		$pag = $this->paginate($pag);
		$pag['total_rows'] =  $this->getEM()->getRepository('\Entity\ShProduct')->total_rows($pag);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['product'] = $this->getEM()->getRepository('\Entity\ShProduct')->backendPaginate($pag);

		$this->render('product/admin_index',array('back.js'));
	}
	public function mod_index($sortBy = 'id', $sortOrder = 'desc'){
		$pag  = array(
			'table' => 'Product',
			'uri_segment' => 6,
			//de sau
			'sort' => true,
			//so luong item tren 1 page
			'per_page' =>12,
			//de say
			'sortList'=>array('stt'=>'id','name'=>'name','ngay'=>'date','binh-luan'=>'comment','luot-xem'=>'view','nhap'=>'draft'),
			'base_url' => '/mod/product/index',
			//de sau
			'sortBy' => $sortBy, 'sortOrder' => $sortOrder
		);

		$pag = $this->paginate($pag);
		$pag['total_rows'] =  $this->getEM()->getRepository('\Entity\ShProduct')->total_rows($pag);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['product'] = $this->getEM()->getRepository('\Entity\ShProduct')->backendPaginate($pag);

		$this->render('product/mod_index',array('back.js'));
	}
	public function admin_category($id = null, $sortBy = 'id', $sortOrder = 'desc'){
		$em = $this->getEM();
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/admin/product');
		endif;
		
		$cat = $this->getEM()->getRepository('Entity\ShCategory')->findOneById($id);
		if(empty($cat)):
			$this->session->set_flashdata('error','Không có chủng loại này');
			redirect('/admin/product');
		endif;
		
		$pag  = array(
			'table' => 'Product',
			'uri_segment' => 7,
			//de sau
			'sort' => true,
			//so luong item tren 1 page
			'per_page' =>8,
			//de say
			'sortList'=>array('stt'=>'id','name'=>'name','ngay'=>'date','binh-luan'=>'comment','luot-xem'=>'view','nhap'=>'draft'),
			'base_url' => '/admin/product/category/'.$id,
			'sortBy' => $sortBy, 'sortOrder' => $sortOrder,
			'condition' => array('category' => $cat)
		);

		$pag = $this->paginate($pag);
		
		$pag['total_rows'] =  $this->getEM()->getRepository('\Entity\ShProduct')->total_rows_cat($cat);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['product'] = $this->getEM()->getRepository('\Entity\ShProduct')->backendPaginate($pag);

		$this->render('product/admin_index',array('back.js'));
		
	}
	public function mod_category($id = null, $sortBy = 'id', $sortOrder = 'desc'){
		$em = $this->getEM();
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/mod/product');
		endif;
		
		$cat = $this->getEM()->getRepository('Entity\ShCategory')->findOneById($id);
		if(empty($cat)):
			$this->session->set_flashdata('error','Không có chủng loại này');
			redirect('/mod/product');
		endif;
		
		$pag  = array(
			'table' => 'Product',
			'uri_segment' => 7,
			
			'sort' => true,
			
			'per_page' =>8,
			
			'sortList'=>array('stt'=>'id','name'=>'name','ngay'=>'date','binh-luan'=>'comment','luot-xem'=>'view','nhap'=>'draft'),
			'base_url' => '/mod/product/category/'.$id,
			'sortBy' => $sortBy, 'sortOrder' => $sortOrder,
			'condition' => array('category' => $cat)
		);

		$pag = $this->paginate($pag);
		
		$pag['total_rows'] =  $this->getEM()->getRepository('\Entity\ShProduct')->total_rows_cat($cat);
		$this->pagination->initialize($pag);
		$this->data['pagination_link'] = $this->pagination->create_links();
		$this->data['product'] = $this->getEM()->getRepository('\Entity\ShProduct')->backendPaginate($pag);

		$this->render('product/mod_index',array('back.js'));
	}
	public function admin_shutdown($id){
		$em = $this->getEM();
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/admin/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/admin/product');
		endif;
		
		$status = $product->getStatus();
		$product->setStatus(!$status);
		$this->getEM()->persist($product);
		$this->getEM()->flush();
		$this->log(6,array($this->data['user']));
		redirect('/admin/product');
	}
	public function mod_shutdown($id){
		$em = $this->getEM();
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/mod/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/mod/product');
		endif;
		
		$status = $product->getStatus();
		$product->setStatus(!$status);
		$this->getEM()->persist($product);
		$this->getEM()->flush();
		$this->log(6,array($this->data['user']));
		redirect('/mod/product');
	}
	public function admin_edit($id = null){
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/admin/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/admin/product');
		endif;
		
		$this->data['cat'] = $this->getEM()->getRepository('Entity\ShCategory')->findAll();
		$this->data['list_color'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 2,
			'status' => 1
		));
		$this->data['list_size'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 3,
			'status' => 1
		));
		
		$this->data['color'] = $this->getEM()->getRepository('Entity\ShProduct')->findProductExtension($id);
		$this->data['size'] = $this->getEM()->getRepository('Entity\ShProduct')->findProductExtension($id, 3);
		
		$this->validation();
		if($this->input->post() && $this->form_validation->run('product')):
			
			$rep = $this->getEM()->getRepository('Entity\ShProduct');
			$insert = $rep->edit_product($product, $this->input);
			if($insert):
				$this->log(10,array($this->data['user']));
				$this->session->set_flashdata('success', 'Chỉnh sửa sản phẩm thành công');
				redirect('/admin/product');
			else:
				$this->data['flash'] = array('error' => 'Lỗi sql, thử lại');
			endif;
		endif;
		
		$this->data['product'] = $product;
		$this->render('product/admin_edit');
	}
	public function mod_edit($id = null){
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/mod/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/mod/product');
		endif;
		
		$this->data['cat'] = $this->getEM()->getRepository('Entity\ShCategory')->findAll();
		$this->data['list_color'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 2,
			'status' => 1
		));
		$this->data['list_size'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 3,
			'status' => 1
		));
		
		$this->data['color'] = $this->getEM()->getRepository('Entity\ShProduct')->findProductExtension($id);
		$this->data['size'] = $this->getEM()->getRepository('Entity\ShProduct')->findProductExtension($id, 3);
		
		$this->validation();
		if($this->input->post() && $this->form_validation->run('product')):
			
			$rep = $this->getEM()->getRepository('Entity\ShProduct');
			$insert = $rep->edit_product($product, $this->input);
			if($insert):
				$this->log(10,array($this->data['user']));
				$this->session->set_flashdata('success', 'Chỉnh sửa sản phẩm thành công');
				redirect('/mod/product');
			else:
				$this->data['flash'] = array('error' => 'Lỗi sql, thử lại');
			endif;
		endif;
		
		$this->data['product'] = $product;
		$this->render('product/mod_edit');
	}
	public function admin_add(){
		
		$this->data['cat'] = $this->getEM()->getRepository('Entity\ShCategory')->findBy(array(), array('name' => 'ASC'));
		$this->data['list_color'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 2,
			'status' => 1
		));
		$this->data['list_size'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 3,
			'status' => 1
		));
		
		$product = array();
		$this->validation();
		if($this->input->post()): //&& $this->form_validation->run('product')):
			$product = new \Entity\ShProduct();
			$rep = $this->getEM()->getRepository('Entity\ShProduct');
			$insert = $rep->edit_product($product, $this->input);
			if($insert):
				$this->log(6,array($this->data['user']));
				$this->session->set_flashdata('success', 'Chỉnh sửa sản phẩm thành công');
				redirect('/admin/product');
			else:
				$this->data['flash'] = array('error' => 'Lỗi sql, thử lại');
			endif;
		endif;
		
		$this->data['product'] = $product;
		$this->render('product/admin_add');
	}
	public function mod_add(){
		$this->data['cat'] = $this->getEM()->getRepository('Entity\ShCategory')->findBy(array(), array('name' => 'ASC'));
		$this->data['list_color'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 2,
			'status' => 1
		));
		$this->data['list_size'] = $this->getEM()->getRepository('Entity\ShExtension')->findBy(array(
			'type' => 3,
			'status' => 1
		));
		
		$product = array();
		$this->validation();
		if($this->input->post()): //&& $this->form_validation->run('product')):
			$product = new \Entity\ShProduct();
			$rep = $this->getEM()->getRepository('Entity\ShProduct');
			$insert = $rep->edit_product($product, $this->input);
			if($insert):
				$this->log(6,array($this->data['user']));
				$this->session->set_flashdata('success', 'Chỉnh sửa sản phẩm thành công');
				redirect('/mod/product');
			else:
				$this->data['flash'] = array('error' => 'Lỗi sql, thử lại');
			endif;
		endif;
		
		$this->data['product'] = $product;
		$this->render('product/mod_add');
	}
	public function admin_delete($id = null){
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/admin/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/admin/product');
		endif;
		
		try {
			$product->setStatus(0);
			$this->getEM()->persist($product);
			$this->getEM()->flush();
			$this->log(3,array($this->data['user']));
		} catch (Exception $e) {
			$this->data['flash'] = array('error' => $e->getMessage());
		}
		
		redirect('/admin/product');
	}
	public function mod_delete($id = null){
		$id = (int)$id;
		if(empty($id) || !is_int($id)):
			$this->session->set_flashdata('error','Sai mã sản phẩm');
			redirect('/mod/product');
		endif;
		
		$product = $this->getEM()->getRepository('Entity\ShProduct')->findOneById($id);
		if(empty($product)):
			$this->session->set_flashdata('error','Không có sản phẩm này');
			redirect('/mod/product');
		endif;
		
		try {
			$product->setStatus(0);
			$this->getEM()->persist($product);
			$this->getEM()->flush();
			$this->log(3,array($this->data['user']));
		} catch (Exception $e) {
			$this->data['flash'] = array('error' => $e->getMessage());
		}
		
		redirect('/mod/product');
	}
}